package com.epro.standard.frontend.util;

import javax.servlet.http.HttpServletRequest;

public final class EproDBPreparedStatement implements java.io.Serializable {

    private EproDBConnectionPoolManager poolManager;
    //	private		java.sql.PreparedStatement				preparedStatement ;
    private EproDBConnection dbConnection;
    private java.sql.Connection connection;
    //	private		HttpServletRequest							request ;

    public EproDBPreparedStatement(HttpServletRequest request) throws Exception {

        this.dbConnection = new EproDBConnection(request);
        //		this.request = request ;
        this.locateDBServer();
    }

    public EproDBPreparedStatement(String driver, String url, String userName, 
                                   String password) throws Exception {

        this.dbConnection = new EproDBConnection();
        this.dbConnection.setJdbcDriver(driver);
        this.dbConnection.setUrl(url);
        this.dbConnection.setDbUserName(userName);
        this.dbConnection.setDbPassword(password);
        this.locateDBServer();
    }

    private void locateDBServer() throws Exception {
        String url = this.dbConnection.getUrl();

        if (url.indexOf("@") >= 0 && url.indexOf(":") >= 0) {
            String ipServer = url.substring(url.indexOf("@") + 1);
            int port = 
                Integer.parseInt(ipServer.substring(ipServer.indexOf(":") + 1, 
                                                    ipServer.lastIndexOf(":")));
            ipServer = ipServer.substring(0, ipServer.indexOf(":"));
            DBServer dbServer = new DBServer(ipServer, port);
            try {
                dbServer.locateServer();
            } catch (java.io.IOException ie) {
                System.out.println("Found error exception while initialize\n	Cannot locate Database Server");
            }
        } else {
            throw new Exception("Database url out of format");
        }
    }

    public java.sql.PreparedStatement preparedStatement(EproDBConnectionPoolManager dbConnectionPoolManager, 
                                                        String sqlStatement) throws Exception {

        if (!dbConnectionPoolManager.isInitialize()) {
            System.out.println("must init");
            dbConnectionPoolManager.setDBConnection(this.dbConnection);
            dbConnectionPoolManager.initializePool();
        }

        this.poolManager = dbConnectionPoolManager;
        this.connection = dbConnectionPoolManager.getConnection();
        return connection.prepareStatement(sqlStatement);
    }

    public void close() {
        this.poolManager.releaseConnection(this.connection);
    }
}

